<template>
  <div>
    <el-upload
      class="avatar-uploader"
      :action="upLoadUrl"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="result.dataURL" :src="result.dataURL" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    <el-dialog v-model="dialogVisible" title="头像裁剪">
      <div class="cropperOut">
        <VuePictureCropper
          :boxStyle="{
            width: '100%',
            height: '100%',
            backgroundColor: '#f8f8f8',
            margin: 'auto',
          }"
          :img="pic"
          :options="{
            viewMode: 1,
            dragMode: 'crop',
            aspectRatio: 16 / 9,
          }"
        />
        <Button @click="clear">清除</Button>
        <Button @click="reset">重置</Button>
        <Button @click="getResult">裁切</Button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, getCurrentInstance,reactive, ref } from "vue";
import VuePictureCropper, { cropper } from "vue-picture-cropper";
interface Result {
  dataURL: string
  blobURL: string
}
export default defineComponent({
  name: "Cropper",
  components: {
    VuePictureCropper,
  },
  props:{
      upLoadUrl:{
          type:String,
          default(){
              return ''
          }
      }
  },
  setup() {
    let imageUrl = ref("");
    const dialogVisible = ref<boolean>(false);
    const handleAvatarSuccess = (res, file) => {
      console.log(file);
    };
    const result: Result = reactive({
      dataURL: '',
      blobURL: '',
    })
    const pic = ref<string>("");
    const beforeAvatarUpload = (file) => {
      console.log(file);
      const reader: FileReader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = (): void => {
        // 更新裁切弹窗的图片源
        pic.value = String(reader.result);
        imageUrl.value = String(reader.result);
        // 显示裁切弹窗
        dialogVisible.value = true;
      };
      return false;
    };
    /**
     * 获取裁切结果
     */
    const getResult = async (): Promise<void> => {
      // console.log(cropper)
      // 获取生成的base64图片地址
      const base64: string = cropper.getDataURL()
      // 获取生成的blob文件信息
      const blob: Blob = await cropper.getBlob()
      // 获取生成的file文件信息
      const file = await cropper.getFile({
        fileName: '测试文件名，可不传',
      })
      console.log('{ base64, blob, file }',{ base64, blob, file })
      // 把base64赋给结果展示区
      result.dataURL = base64
      try {
        result.blobURL = URL.createObjectURL(blob)
      } catch (e) {
        result.blobURL = ''
      }
      // 隐藏裁切弹窗
      dialogVisible.value = false
    }
    /**
     * 清除裁切框
     */
    const clear = (): void => {
      cropper.clear()
    }
    /**
     * 重置默认的裁切区域
     */
    const reset = (): void => {
      cropper.reset()
    }


    return {
      imageUrl,
      handleAvatarSuccess,
      beforeAvatarUpload,
      dialogVisible,
      pic,
      getResult,
      clear,
      reset,
      result
    };
  },
});
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.cropperOut {
  width: 300px;
  height: 300px;
}
</style>
